import { onActivated, onMounted, onUnmounted, ComponentPublicInstance, Ref } from 'vue'
import { BodyScrollEndEvent } from 'ag-grid-community'

export default function scrollStateKeep(
  ownEvents: Record<string, (...params: any) => void>,
  agGridRef: Ref<ComponentPublicInstance>
): void {
  let xViewport: HTMLElement | null // ag-grid 出现水平方向滚动条的 元素
  let yViewport: HTMLElement | null // ag-grid 出现垂直方向滚动条的 元素
  onMounted(() => {
    const { $el } = agGridRef.value

    xViewport = $el.querySelector('.ag-body-horizontal-scroll-viewport')
    yViewport = $el.querySelector('.ag-body-viewport')
  })

  let left: number | undefined
  let top: number | undefined

  const scrollToPrevState = (direction: 'x' | 'y') => {
    if (direction === 'x' && typeof left === 'number' && xViewport) {
      xViewport.scrollLeft = left
    }
    if (direction === 'y' && typeof top === 'number' && yViewport) {
      yViewport.scrollTop = top
    }
  }
  let isActivated = false
  onActivated(() => {
    isActivated = true

    scrollToPrevState('y')
  })

  ownEvents.onBodyScrollEnd = (event: BodyScrollEndEvent) => {
    if (isActivated) {
      isActivated = false

      scrollToPrevState('x')

      return
    }

    left = event.left
    top = event.top
  }

  onUnmounted(() => {
    xViewport = null
    yViewport = null

    left = undefined
    top = undefined
  })
}